#include <REG51.H>
#include <Stopwatch.h>
#include <Mode.h>
#include <Key.h>

// 存储秒表数据
Stopwatch_TypeDef Stopwatch_buff;

/**
 * @brief  秒表功能初始化
 * @param  None
 * @retval None
 */
void Stopwatch_init(void)
{
    Stopwatch_buff.status = Stopwatch_status_stop;
    Stopwatch_buff.millisecond = 0;
    Stopwatch_buff.second = 0;
    Stopwatch_buff.minute = 0;
    Stopwatch_buff.hour = 0;
}

/**
 * @brief  秒表复位
 * @param  None
 * @retval None
 */
void Stopwatch_reset(void)
{
    Stopwatch_buff.millisecond = 0;
    Stopwatch_buff.second = 0;
    Stopwatch_buff.minute = 0;
    Stopwatch_buff.hour = 0;
}

/**
 * @brief  该函数用于更新秒表数据，功能为当有秒表数据发生改变时，检查是否需要进位
 * @param  None
 * @retval None
 */
void Stopwatch_updata_Data(void)
{
    // 毫秒进位
    if (Stopwatch_buff.millisecond < 100)
    {
        return;
    }
    Stopwatch_buff.millisecond = 0;
    Stopwatch_buff.second++;

    // 秒进位
    if (Stopwatch_buff.second < 60)
    {
        return;
    }
    Stopwatch_buff.second = 0;
    Stopwatch_buff.minute++;

    // 分进位
    if (Stopwatch_buff.minute < 60)
    {
        return;
    }
    Stopwatch_buff.minute = 0;
    Stopwatch_buff.hour++;

    // 秒表允许的最大计时时间为 24：00：00：00
    // 当秒表达到最大允许计时时间时，秒表将自动停止计时
    if (Stopwatch_buff.hour >= 24)
    {
        Stopwatch_buff.status = Stopwatch_status_stop;
    }
}

/**
 * @brief  秒表的控制函数，提供秒表的控制功能
 * @param  None
 * @retval None
 */
void Stopwatch_ctrl(void)
{
    while (System_Mode == Mode_Stopwatch)
    {
        switch (Key_Scan())
        {
        case Key0_Down:
            if (Stopwatch_buff.status == Stopwatch_status_stop)
            {
                System_Mode = Mode_Clock;
            }
            break;

        case Key1_Down:
            if (Stopwatch_buff.status == Stopwatch_status_start)
            {
                Stopwatch_buff.status = Stopwatch_status_suspend;
            }
            else if (Stopwatch_buff.status == Stopwatch_status_suspend)
            {
                Stopwatch_buff.status = Stopwatch_status_start;
            }
            else if (Stopwatch_buff.status == Stopwatch_status_stop)
            {
                Stopwatch_reset();
                Stopwatch_buff.status = Stopwatch_status_start;
            }
            break;

        case Key2_Down:
            if (Stopwatch_buff.status == Stopwatch_status_start || Stopwatch_buff.status == Stopwatch_status_suspend)
            {
                Stopwatch_buff.status = Stopwatch_status_stop;
            }
            break;
        }
    }
}
